#!/bin/bash
#

function package_install(){
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    yum -y install cobbler cobbler-web pykickstart httpd dhcp tftp xinetd 
    yum -y install debmirror
    yum -y install fence-agents
}


function startallservice(){
    systemctl start httpd.service
    systemctl start cobblerd
    systemctl start rsyncd.service
    systemctl start dhcpd.service
    systemctl start tftp.service
}

function stopallservice(){
    systemctl stop httpd.service
    systemctl stop cobblerd
    systemctl stop rsyncd.service
    systemctl stop dhcpd.service
    systemctl stop tftp.service
}


function configure(){
    read -p "please input a ip address: " address

    sed -i -e 's/^server:.*/server: $address/' /etc/cobbler/settings
    sed -i -e 's/^next_server:.*/next_server: 192.168.152.128/' /etc/cobbler/settings 
    sed -i -e 's/disable.*= yes/disable = no/' /etc/xinetd.d/tftp 
    cobbler get-loaders
    systemctl start rsyncd.service
    systemctl enable rsyncd.service    

    sed -i 's/^@dists="sid"/#@dists="sid"/' /etc/debmirror.conf 
    sed -i 's/^@arches="i386"/#@arches="i386"/' /etc/debmirror.conf 
    sed -i -e 's/^default_password_crypted:.*/default_password_crypted: "$1$cobbler$M6SE55xZodWc9.vAKLJs6."/' /etc/cobbler/settings 

    systemctl restart cobblerd.service
    cobbler check
    cobbler sync

    sed -i -e 's/^manage_dhcp:.*/manage_dhcp: 1/' /etc/cobbler/settings 
    sed -i -e 's/^pxe_just_once:.*/pxe_just_once: 1/' /etc/cobbler/settings 
    
    systemctl restart cobblerd.service
    cobbler check
    cobbler sync
}


function dhcp_configure(){
    sed -i -e 's/^subnet.*/subnet 192.168.152.0 netmask 255.255.255.0 {/' /etc/cobbler/dhcp.template 
    sed -i -e 's/.*option routers.*/     option routers             192.168.152.2;/' /etc/cobbler/dhcp.template 
    sed -i -e 's/.*option domain-name-servers.*/     option domain-name-servers 114.114.114.114;/' /etc/cobbler/dhcp.template 
    sed -i -e 's/.*range dynamic-bootp        .*/     range dynamic-bootp        192.168.152.100 192.168.152.200;/' /etc/cobbler/dhcp.template 
}


function restart(){
    systemctl restart httpd.service
    systemctl restart cobblerd.service
    systemctl restart rsyncd.service
    systemctl restart dhcpd.service
    systemctl restart tftp.service
}



case "$1" in
    start)
        startallservice
    ;;
    stop)
        stopallservice
    ;;
    restart)
        restart
    ;;
    packages)
        package_install
    ;;
    config)
        configure
    ;;
    dhcp)
        dhcp_configure
    ;;
    *)
        echo "hello world"
    ;;
esac